package controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import controller.ClientHandler;

/**
 * The main controller
 * 
 * The is the entry point for the email server application. From here onwards,
 * the server is started and it manager all the incoming and outgoing client
 * requests.
 * 
 * @author MUSAB
 * 
 */
public class Server {

	// This is the socket to which all clients shall connect;
	private ServerSocket mySocket;
	
	/**
	 * Constructor
	 * @param port
	 * @throws IOException 
	 */
	public Server(Integer port) throws IOException{
		mySocket = new ServerSocket(port);
		startListening();
	}
	
	/**
	 * Starts listening to the incoming connections
	 */
	private void startListening() {
		
		System.out.println("Server started, waiting for connections...");

		while (true) {
			try {
				new Thread(new ClientHandler(mySocket.accept())).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
